/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tfisher.views;

import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import org.json.simple.parser.ParseException;
import org.springframework.stereotype.Component;
import tfisher.controllers.ResultsController;
import tfisher.dao.Keywords;
import tfisher.entities.Media;
import tfisher.entities.Tweet;
import tfisher.utils.HistoryParser;

/**
 *
 * @author Theodore Crysochoidis
 */
@Component
public class ResultsForm extends javax.swing.JFrame implements Observer {

  private static int start = 0, end = 50;
  private static String newOld = new String();
      DefaultTableModel _model; 
    public ResultsForm() {
        super("Results");
        initComponents();
        centerFrame(); 
        createControls();
        _model = (DefaultTableModel) tweetsTable.getModel(); 
        
        setDefaultCloseOperation(HIDE_ON_CLOSE);
    }
    public ResultsController _resultsController;   
    
    public void addController( ResultsController controller )
    {
        _resultsController = controller;
    }

    public void createControls()
    {      
      keywordsCombo.addActionListener(new ComboBoxListener());
      historyCobmo.addActionListener(new ComboBoxListener());
      historyBtn.addActionListener(new FetchHistoryKeywords());     
      nexBtn.addActionListener(new NextBtnListener());
      firstBtn.addActionListener(new NextBtnListener());
      
    }
    public void populateComboKeywords( Keywords keywords )
    {
        String [] keywordsArray = keywords.getArrayOfKeywords();      
        keywordsCombo.removeAllItems();       
        for ( int i = 0; i < keywordsArray.length; i++ )
        { 
             keywordsCombo.addItem(keywordsArray[i]);
        }       
    }
    private void centerFrame() 
   {
       Dimension windowSize = getSize();
       GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
       Point centerPoint = ge.getCenterPoint();
       int dx = centerPoint.x - windowSize.width / 2;
       int dy = centerPoint.y - windowSize.height / 2;    
       setLocation(dx, dy);
       setResizable(false);
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        keywordsCombo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        panel1 = new java.awt.Panel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tweetsTable = new javax.swing.JTable();
        nexBtn = new javax.swing.JButton();
        firstBtn = new javax.swing.JButton();
        historyCobmo = new javax.swing.JComboBox();
        historyBtn = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        keywordsCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] {  }));

        jLabel1.setText("New keywords");

        tweetsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Text", "Created at", "Picture"
            }
        ));
        jScrollPane1.setViewportView(tweetsTable);

        nexBtn.setText("Next >>");

        firstBtn.setText("First");

        javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
        panel1.setLayout(panel1Layout);
        panel1Layout.setHorizontalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1014, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(26, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(firstBtn)
                .addGap(18, 18, 18)
                .addComponent(nexBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(73, 73, 73))
        );
        panel1Layout.setVerticalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 392, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nexBtn)
                    .addComponent(firstBtn))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        historyBtn.setText("Fetch All Keywords");

        jLabel2.setText("All keywords (history) ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 1046, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(keywordsCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(82, 82, 82)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(historyCobmo, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(historyBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(keywordsCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(historyCobmo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(historyBtn))
                .addGap(57, 57, 57)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ResultsForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ResultsForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ResultsForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ResultsForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ResultsForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton firstBtn;
    private javax.swing.JButton historyBtn;
    private javax.swing.JComboBox historyCobmo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JComboBox keywordsCombo;
    private javax.swing.JButton nexBtn;
    private java.awt.Panel panel1;
    private javax.swing.JTable tweetsTable;
    // End of variables declaration//GEN-END:variables

    public void update(Observable o, Object arg) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
    
    class NextBtnListener implements ActionListener
    {                
        public void actionPerformed(ActionEvent e) 
        {
            if ( newOld.isEmpty() )
                {
                    JOptionPane.showMessageDialog(null,
                            "You have to choose from new or older keywords combobox","Choose keyword",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            if ( e.getSource() == firstBtn )
            {                
                start = 0;
                end = 50;
            }
           if ( "old".equals(newOld) )//old tweets
           {
               String selectedItem = new String();           
                _model.setRowCount(0);                       
                selectedItem = String.valueOf(historyCobmo.getSelectedItem());
                List <Tweet> tweets = _resultsController.
                        findTweetsByKeyword(selectedItem,true, start, end );                 
                if ( tweets.isEmpty() )
                {
                    JOptionPane.showMessageDialog(null,
                            "No results for this keyword","No results",
                            JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                int i = 0;      
                String picture = new String();
                for (Tweet tweet : tweets) 
                {   
                   Media media = _resultsController.getUrl(tweet.getIdStr());
                   if ( media != null)
                   {
                       picture = media.getMediaUrl();
                   }
                   else
                   {
                       picture = "";
                   }                      
                    i++;                    
                   
                    _model.insertRow(_model.getRowCount(), new Object[]
                    { tweet.getText(), tweet.getCreatedAt(), picture});
                }         
                resizeColumnWidth(tweetsTable);
               
                start = end;
                end = end+= 50;  
                
           }
           else if ( "new".equals(newOld) )//new tweets
           {
               
                String selectedItem = new String();
                _model.setRowCount(0); 
                selectedItem = String.valueOf(keywordsCombo.getSelectedItem());
                List <Tweet> tweets = _resultsController.findTweetsByKeyword(selectedItem,false, start, end );
                
                      
                if ( tweets.isEmpty() )
                {
                    JOptionPane.showMessageDialog(null, "No results for this keyword","No results", JOptionPane.INFORMATION_MESSAGE);
                        return;
                }
                int i = 0;               
                String picture = new String();
                for (Tweet tweet : tweets) 
                {   
                      Media media = _resultsController.getUrl(tweet.getIdStr());
                      if ( media != null)
                      {
                          picture = media.getMediaUrl();
                      }
                      else
                      {
                          picture = "";
                      }                      
                       i++;
                       _model.insertRow(_model.getRowCount(), new Object[]
                       { tweet.getText(), tweet.getCreatedAt(), picture});
                }
                System.out.println("RESULTS ARE: "+i);
                   resizeColumnWidth(tweetsTable);
               
                    _resultsController.updateStickyBit(selectedItem, tweets );  
           }
        }//end of actionPerformed
        
    }    
    
   
    class ComboBoxListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e) {                      
            if ( e.getSource() == keywordsCombo )//new results
            {
                start = 0; end = 50;
                newOld = "new";
            }
            else if ( e.getSource() == historyCobmo )//old results
            {
                start = 0; end = 50;
                newOld = "old";
            }
        }
        
    }
      
    class FetchHistoryKeywords implements ActionListener
    {
        HistoryParser historyParser = new HistoryParser();
        public void actionPerformed(ActionEvent e) 
        {          
            ArrayList < String > historyKeywords;
            historyCobmo.removeAllItems();  
            try {
                    historyKeywords = historyParser.parseKeywords();                         
                    for ( int i = 0; i < historyKeywords.size(); i++ )
                    { 
                         historyCobmo.addItem(historyKeywords.get(i));
                    }
            } catch (IOException ex) {
                Logger.getLogger(ResultsForm.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParseException ex) {
                Logger.getLogger(ResultsForm.class.getName()).log(Level.SEVERE, null, ex);
            }            
        }
        
    }
       
    
    public void resizeColumnWidth(JTable table) {
    final TableColumnModel columnModel = table.getColumnModel();
    for (int column = 0; column < table.getColumnCount(); column++) {
        int width = 50; // Min width
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer renderer = table.getCellRenderer(row, column);
            java.awt.Component comp = table.prepareRenderer(renderer, row, column);
            width = Math.max(comp.getPreferredSize().width, width);
        }
        columnModel.getColumn(column).setPreferredWidth(width);
    }
}
    
    
 
}
